package com.us.usws.batch;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import net.iwsh.core.common.GlobalConfig;
import net.iwsh.core.exception.GenericRuntimeException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.us.usws.batch.resimp.FileListVideoWalker;
import com.us.usws.batch.resimp.ResDescFile;
import com.us.usws.batch.resimp.channel.CSVChannel;
import com.us.usws.batch.resimp.channel.CSVChannelImpWorker;
import com.us.usws.batch.resimp.region.CSVRegion;
import com.us.usws.batch.resimp.region.CSVRegionImpWorker;
import com.us.usws.batch.resimp.result.ResImpResult;
import com.us.usws.batch.resimp.video.CSVVideo;
import com.us.usws.batch.resimp.video.CSVVideoImpWorker;

public class BatchResImportor {
	private static Log log = LogFactory.getFactory().getInstance(BatchResImportor.class);

	private static final String CHANNEL_DESC_PATH = GlobalConfig.getString("BatchImport/ChannelDescFile");
	private static final String REGION_DESC_PATH = GlobalConfig.getString("BatchImport/RegionescFile");
	private static final String VIDEO_ENTRY = GlobalConfig.getString("BatchImport/VideoEntry");

	/**
	 * batch region import
	 * @return
	 */
	public ResImpResult impRegions() {
		CSVRegionImpWorker w = new CSVRegionImpWorker();
		try {
			log.info("Importing regions from [" + REGION_DESC_PATH + "].");
			return w.loadCsv(new ResDescFile(REGION_DESC_PATH), CSVRegion.class).imp();
		} catch (IOException e) {
			throw new GenericRuntimeException("Error of batch region import.", e);
		}
	}

	/**
	 * batch channel import
	 * @param cleanBeforeInsert
	 * @return
	 */
	public ResImpResult impChannel(boolean cleanBeforeInsert) {
		CSVChannelImpWorker w = new CSVChannelImpWorker(cleanBeforeInsert);
		try {
			log.info("Importing channel from [" + CHANNEL_DESC_PATH + "].");
			return w.loadCsv(new ResDescFile(CHANNEL_DESC_PATH), CSVChannel.class).imp();
		} catch (IOException e) {
			throw new GenericRuntimeException("Error of batch channel import.", e);
		}
	}

	/**
	 * batch video import
	 * @param cleanBeforeInsert
	 * @return
	 * @throws IOException
	 */
	public ResImpResult impVideo(boolean cleanBeforeInsert) throws IOException {
		ResImpResult ret;
		FileListVideoWalker walker = new FileListVideoWalker();
		Files.walkFileTree(Paths.get(VIDEO_ENTRY), walker);
		List<ResDescFile> result = walker.getResult();
		if (result == null || result.isEmpty()) {
			ret = new ResImpResult();
			ret.setSummaryMsg("没有找到任何视频描述文件（" + FileListVideoWalker.DESC_FILE + ")。");
			return ret;
		}

		CSVVideoImpWorker w = new CSVVideoImpWorker(cleanBeforeInsert);
		for (ResDescFile each : result) {
			w.appendCsv(each, CSVVideo.class);
		}
		log.info(">>>>>>> ALL Done!");
		return w.imp();
	}

}
